<template>
  <a-card class="min-h-[68px] rounded my-[10px]" :body-style="{ padding: '0px 10px', minHeight: '700px' }"
    :bordered="false">
    <!-- 头部返回列表功能 -->
    <template #extra>
      <a-button class="border-none" icon="rollback" @click="rollback">{{
        $t("app.setting.themecolor.rr99")
      }}</a-button>
    </template>
    <!-- 正文头部 -->
    <div slot="title">
      <a-space>
        <div class="ty"></div>
        {{ $t("user.verification-code.required1115661105720") }}
      </a-space>
    </div>
    <!-- 头部导航+查看RPA详情 -->
    <div style="margin: 30px 10px 0px 20px">
      <div style="display: flex; justify-content: space-between">
        <!-- 查看详情 -->
        <div style="
            margin-left: 20px;
            margin-top: -6px;
            right: 0;
            position: absolute;
            margin-right: 20px;
          ">
          <rpaDetail :rpaDetailId="id" :lang="lang" />
        </div>
      </div>
    </div>
    <!-- 主列表 -->
    <div class="card-right">
      <a-row>
        <a-space class="mb-[15px]">
          <div class="tags"></div>
          {{ $t("user.verification-code.required1115661105760") }}
        </a-space>
        <a-row type="flex">
          <a-col :span="18">
            <a-table ref="table" size="middle" class="h-full overflow-x-auto" :pagination="dpiaSimpleEstimatePagination"
              :dataSource="dpiaSimpleEstimateLists" :rowKey="(record) => record.Id">
              <a-table-column key="DpiaChapterTitle" data-index="DpiaChapterTitle">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required1115661105761")
                }}</span>
              </a-table-column>
              <a-table-column key="DpiaChapterDcoRemark" data-index="DpiaChapterDcoRemark">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required1115661105762")
                }}</span>
                <span key="DpiaChapterDcoRemark" slot-scope="text">
                  <span v-html="text"></span>
                </span>
              </a-table-column>
            </a-table>
          </a-col>
          <!-- <a-col style="
              margin-left: 20px;
              height: 200px;
              overflow-y: scroll;
              padding-top: 5px;
            " :span="11">
            <a-timeline>
              <a-timeline-item v-for="item in transferList" :key="item.Id">
                <div>
                  {{ item.DpiaCommentsDCO + item.DpiaCommentsCreatetime }}
                </div>
                <div>
                  {{ $t("user.verification-code.required1115661105763") }}：{{
                    item.DpiaCommentsTypeStr
                  }}
                </div>
                <div>
                  <span>{{
                    $t("user.verification-code.required111566181")
                  }}</span>{{ item.DpiaCommentsInfo ? item.DpiaCommentsInfo : "无" }}
                </div>
              </a-timeline-item>
            </a-timeline>
          </a-col> -->
        </a-row>

        <!-- Action列表 -->
        <div v-if="pia">
          <a-space class="mb-[15px]">
            <div class="tags"></div>
            {{ $t("user.verification-code.required1115661105764") }}
          </a-space>
          <div class="mb-[20px]">
            <a-space>
              <!-- <a-button
              type="primary"
              icon="plus"
              @click="createActions"
              v-if="state != 'see'"
              >{{ $t("user.verification-code.required11156611052") }}
            </a-button> -->
              <!-- RISK触发 -->
              <a-button type="danger" icon="plus" :disabled="riskButtom" @click="setActionToRisk">{{
                $t("user.verification-code.required1115661105765") }}
              </a-button>
            </a-space>
          </div>
          <div class="mb-[70px]">
            <a-table ref="table" size="middle" :row-selection="rowSelection" class="h-full overflow-x-auto mb-[30px]"
              :dataSource="dpiaSimpleActionLists" :pagination="false" :rowKey="(record) => record.Id"
              style="min-width: 800px">
              <!-- <a-table-column key="DpiaActionIdTag" data-index="DpiaActionIdTag">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required11156611057")
                }}</span>
              </a-table-column> -->
              <a-table-column key="DpiaActionName" data-index="DpiaActionName" width="250px">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required1115661105711")
                }}</span>
              </a-table-column>
              <a-table-column key="DpiaActionUserResponsible" data-index="DpiaActionUserResponsible" width="130px">
                <span slot="title" class="min-w-90p" >{{
                  $t("user.verification-code.required111566174")
                }}</span>
              </a-table-column>
              <a-table-column key="DpiaActionCreatetime" data-index="DpiaActionCreatetime" width="160px">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required111566169")
                }}</span>
              </a-table-column>
              <a-table-column key="DpiaActionInfo" data-index="DpiaActionInfo" :ellipsis="true">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required111566173")
                }}</span>
              </a-table-column>
              <!-- 合规状态 -->
              <a-table-column key="DpiaActionStatus" data-index="DpiaActionStatus" width="130px">
                <span slot="title" class="min-w-90p">{{
                  $t("user.verification-code.required.state")
                }}</span>
                <template slot-scope="text, record">
                  <div v-if="record.DpiaActionStatus == 1">
                    <a-badge color="blue" />
                    {{ $t("user.verification-code.required111566133") }}
                  </div>
                  <div v-else-if="record.DpiaActionStatus == 2">
                    <a-badge color="orange" />
                    {{ $t("user.verification-code.required1115661444444") }}
                  </div>
                  <div v-else-if="record.DpiaActionStatus == 3">
                    <a-badge color="purple" />
                    {{ $t("user.verification-code.required1115661455555") }}
                  </div>
                  <div v-else-if="record.DpiaActionStatus == 4">
                    <a-badge color="green" />
                    {{ $t("user.verification-code.required111566146") }}
                  </div>
                  <div v-else-if="record.DpiaActionStatus == 5">
                    <a-badge color="red" />
                    {{ $t("user.verification-code.tobeconfirmed") }}
                  </div>
                </template>
              </a-table-column>
              <a-table-column key="action" :title="$t('menu.exception.not-find')" width="140px">
                <template slot-scope="text, record">
                  <span>
                    <a-button type="link" @click="editActions(record.Id)">{{
                      $t("user.verification-code.required1115661102")
                    }}</a-button>
                    <a-popconfirm :title="$t('user.verification-code.required111566110577225')
                      " :ok-text="$t('user.verification-code.required1166')" :cancel-text="$t('user.email.required11')"
                      @confirm="() => delAction(record)" v-if="state != 'see'">
                      <a-button type="link" size="small">{{
                        $t("menu.exception.trigger")
                      }}</a-button>
                    </a-popconfirm>
                  </span>
                </template>
              </a-table-column>
            </a-table>
            <!-- 分页 -->
            <a-pagination size="small" style="
              float: right;
              right: 0;
              position: absolute;
              margin-top: -420px;
            " v-model="dpiaSimpleActionPagination.page" :total="dpiaSimpleActionPagination.total" hideOnSinglePage
              :pageSize.sync="dpiaSimpleActionPagination.pageSize" @change="actions" />
          </div>
          <div class="mb-[70px]">
            <!--  RISK列表   -->
            <a-space>
              <div class="tags"></div>
              {{ $t("user.verification-code.required1115661105766") }}
            </a-space>
            <div class="mt-[10px]">
              <a-table ref="table" size="middle" class="h-full overflow-x-auto mb-[30px]"
                :dataSource="dpiaSimpleRiskLists" :pagination="false" :rowKey="(record) => record.Id"
                style="min-width: 800px">
                <a-table-column key="RiskId" data-index="RiskId" width="150">
                  <span slot="title">{{
                    $t("user.verification-code.required111566123")
                  }}</span>
                </a-table-column>
                <a-table-column key="RiskName" data-index="RiskName" width="150">
                  <span slot="title">{{
                    $t("user.verification-code.required111566125")
                  }}</span>
                </a-table-column>
                <a-table-column key="RiskSource" data-index="RiskSource" width="150">
                  <span slot="title">{{
                    $t("user.verification-code.required111566126")
                  }}</span>
                </a-table-column>
                <a-table-column key="RiskOwnerUserName" data-index="RiskOwnerUserName" width="150">
                  <span slot="title">{{
                    $t("user.verification-code.required111566128")
                  }}</span>
                </a-table-column>
                <a-table-column key="RiskDcoUserName" data-index="RiskDcoUserName" width="150">
                  <span slot="title">DCO</span>
                </a-table-column>

                <a-table-column key="RiskCreatetime" data-index="RiskCreatetime" width="150">
                  <span slot="title">{{
                    $t("user.verification-code.required111566131")
                  }}</span>
                </a-table-column>
                <a-table-column key="RiskDeadline" data-index="RiskDeadline" width="150">
                  <span slot="title">{{
                    $t("user.verification-code.required111566132")
                  }}</span>
                </a-table-column>

                <a-table-column key="RiskState" :title="$t('app.setting.content-width.fluid')">
                  <template slot-scope="text, record">
                    <span>
                      <div v-if="record.RiskState == 1">
                        <a-badge color="blue" />{{ $t("draft") }}
                      </div>

                      <div v-else-if="record.RiskState == 2">
                        <a-badge color="orange" /> {{ $t("submitted") }}
                      </div>
                      <div v-else-if="record.RiskState == 3">
                        <a-badge color="purple" /> {{ $t("inProgress") }}
                      </div>
                      <div v-else-if="record.RiskState == 4">
                        <a-badge color="green" /> {{ $t("completed") }}
                      </div>
                      <div v-else-if="record.RiskState == 5">
                        <a-badge color="grey" /> {{ $t("toBeEdited") }}
                      </div>
                    </span>
                  </template>
                </a-table-column>
              </a-table>
              <!-- 分页 -->
              <a-pagination size="small" style="
                float: right;
                right: 0;
                position: absolute;
                margin-top: -420px;
              " v-model="dpiaSimpleRiskPagination.page" :total="dpiaSimpleRiskPagination.total" hideOnSinglePage
                :pageSize.sync="dpiaSimpleRiskPagination.pageSize" @change="risks()" />
            </div>
            <span>{{ $t("user.v127") }}:</span>
            <a-date-picker v-model="DpiaNextTime" format="YYYY-MM-DD" show-time
              :placeholder="$t('user.verification-code.required111566157')" @change="onChange" @ok="onOk"
              :disabledDate="disabledDate" />
          </div>
        </div>

      </a-row>
    </div>

    <!-- 下方按钮 -->
    <div :style="{
      position: 'fixed',
      right: 0,
      bottom: 0,
      width: '100%',
      borderTop: '1px solid #e9e9e9',
      padding: '20px 16px',
      background: '#fff',
      textAlign: 'center',
      zIndex: 1,
    }">
      <a-button @click="rollback()" style="margin-right: 20px">{{
        $t("app.setting.themecolor.rr")
      }}</a-button>
      <!-- 生成DPIA评估报告 -->
      <a-button type="primary" :loading="buttonLoading" @click="savePush()" :disabled="state == 'see'"
        style="margin-right: 20px">
        {{ $t("user.verification-code.required1115661105767") }}
      </a-button>
      <!-- 生成报告 -->
      <a-button type="primary" :loading="exportLoading" @click="savePush('see')" v-if="state == 'see' && pia">
        {{ $t("user.verification-code.required111566110576711") }}
      </a-button>
      <a-button type="primary" @click="returnChapter()" v-if="state !== 'see'">
        {{ $t("user.verification-code.returnchapter") }}
      </a-button>
    </div>

    <!-- Action的创建 -->
    <createAction ref="createAction" :questionId="id" @succeed="actions()" />
    <!-- Risk的创建 -->
    <createRisk ref="createRisk" :questionId="id" :actionIds="actionIdGroups" @succeed="risks()" @getList="actions()" />
  </a-card>
</template>

<script>
import {
  dpiaQuestionChapterLists,
  dpiaQuestionInfo,
  dpiaSimpleAnswer,
  dpiaQuestionTopic,
  dpiaQuestionAnswerCreate,
  dpiaQuestionChangeStatus,
  dpiaSimpleAction,
  allDpiaSimpleAction,
  dpiaDcoRemarkInfo,
  dpiaDcoRemarkInfoUpdate,
  dpiaDcoTransfer,
  dpiaDcoBackoff,
  dpiaRiskLists,
  allDpiaRiskLists,
  getItemsChapterRemark,
  transferDetails,
  DpiaUpload,
  dpiaChangeState,
  dpiaSeeSimpleAction,
  createSettime,
  getNextTime,
  dpiaCompleteAssessment,
  isWithdraw,
} from '@/api/dpia/form'
import Readio from './readio.vue'
import Checkbox from './checkbox.vue'
import Esitory from './esitory.vue'
import Four from './four.vue'
import RpaDetail from './components/rpaDetail.vue'
import CreateAction from './components/createAction.vue'
import CreateRisk from './components/createRisk.vue'
import { userQuery } from '@/api/common/form'
import { ristDelAction } from '@/api/risk/form'
import moment from 'moment'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { quesionFindRpaId, rpaDetail } from '@/api/rpa/form'
import axios from 'axios'
import qs from 'qs'

import {
  DpiaList,
} from '@/api/dpia/form'


export default {
  components: {
    Readio,
    Checkbox,
    Esitory,
    Four,
    RpaDetail,
    CreateAction, // 创建Action
    CreateRisk, // 创建RISK
  },
  watch: {
    dcoRemark: async function () {
      try {
        // 更新创建备注
        await dpiaDcoRemarkInfoUpdate({
          DpiaChapterDcoRemark: this.dcoRemark,
          DpiaQid: this.id,
          DpiaChapterId: this.chapterId,
        })
      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
  },
  data() {
    return {
      buttonLoading: false,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          const sRowKeysGroups =  [...new Set(selectedRowKeys)];
          const selectedRowKeysCopy = sessionStorage.getItem('selectedRowKeys');
          const onlyRowKeys = sRowKeysGroups.filter(item => !selectedRowKeysCopy.includes(item));

          if (onlyRowKeys.length > 0) {
            this.riskButtom = false
            this.actionIdGroups = selectedRowKeys
            this.actionDataGroups = selectedRows
            this.rowSelection.selectedRowKeys = [
              ...this.selectedRowKeys,
              ...selectedRowKeys,
            ]
          } else {
            this.rowSelection.selectedRowKeys = [...this.selectedRowKeys]
            this.riskButtom = true
          }
        },
        getCheckboxProps: (record) => ({
          props: {
            checked: record.RiskId !== 0,
            disabled: record.RiskId !== 0, // Column configuration not to be checked
          },
        }),
        selectedRowKeys: [],
      },
      // DCO评估结果
      dcoRemark: undefined,
      dco: undefined,
      // DCO列表
      userList: [],
      // DCO按钮
      dcoButtom: false,
      disabledDate: '',

      current: '',
      value: '',
      visible: false,

      // DCO backoff的状态
      dcoBackoffVisible: false,

      // 配置分页
      dpiaSimpleAnswerPagination: {
        page: 1,
        pageSize: 5,
        total: 0,
      },
      dpiaSimpleActionPagination: {
        page: 1,
        pageSize: 5,
        total: 0,
      },
      dpiaSimpleRiskPagination: {
        page: 1,
        pageSize: 5,
        total: 0,
      },
      dpiaSimpleEstimatePagination: {
        page: 1,
        pageSize: 5,
        total: 0,
        // onChange: this.onchange, // 页码改变时的回调函数
      },

      // 左侧的章节列表
      chapterLists: [],

      // 基础答题信息
      questionnaireInfo: {},

      // 问题和答案数据
      dpiaQuestionTopicAnswer: {},

      // 问卷ID
      id: '',

      // 当前选中章节ID
      chapterId: '',

      // 获取用户问题答案
      dpiaQuestionUserAnswer: {},

      // 当前题型
      topicType: 0,

      // 是否结束
      finishStatus: 0,

      // 已答题的结果
      dpiaQuestionUserLastAnswer: '',

      // 答题章节内容
      dpiaSimpleAnswerLists: [],

      // Action列表
      dpiaSimpleActionLists: [],

      // 评估意见列表
      dpiaSimpleEstimateLists: [],

      // 选中的ActionID列表
      actionIdGroups: [],
      // 选中的ActionData列表
      actionDataGroups: [],
      //RISK列表
      dpiaSimpleRiskLists: [],

      //创建风险按钮状态
      riskButtom: true,
      //转办详情列表
      transferList: [],
      // 整体评估/查看see
      state: '',
      //下次评估时间
      DpiaNextTime: null,
      // 当前语言
      lang: 'zh-EN',
      exportLoading: false,
      ifLoading: false,
      selectedRowKeys: [],
      //特殊题型
      RpaIfCompletedPIA: 0,
      RpaNoPIOrImportantInvolved: 0,
      pia: false,
      isLable: null,
      xiazaiStatus: 0,
      reportUrlC: '',
      reportUrlE: '',
    }
  },
  created() {
    this.init()
    this.getAllSelectedData();
  },
  mounted() {
    const nowLang = localStorage.getItem("lang").includes("zh-EN")
    if (nowLang) {
      this.lang = 'zh-EN'
    } else {
      this.lang = 'zh-CN'
    }
    window.addEventListener('setItemEvent', (e) => {
      if (e.key == 'lang') {
        this.lang = JSON.parse(e.value)
      }
    })
    this.isLable = this.$route.query.isLable;
  },
  methods: {
    async getAllSelectedData() {
      try {
        const pageSize = 5; // 每页显示的数量
        let currentPage = 1; // 当前页码
        let totalPage = 0; // 总页数
        let allSelectedIds = []; // 存储所有选中的行的 Id

        do {
          const { data: dpiaSimpleActionObject } = await dpiaSimpleAction({
            Id: this.id,
            page: currentPage,
            pageSize,
          });
          const { Lists, Total } = dpiaSimpleActionObject;

          // 获取当前页的选中行的 Id
          const selectedIds = Lists
            .filter(item => item.RiskId !== 0)
            .map(item => item.Id);

          allSelectedIds = [...allSelectedIds, ...selectedIds];

          totalPage = Math.ceil(Total / pageSize); // 计算总页数
          currentPage++; 
        } while (currentPage <= totalPage);

        // 更新 selectedRowKeys 和 rowSelection.selectedRowKeys
        this.selectedRowKeys = allSelectedIds;
        this.rowSelection.selectedRowKeys = [...allSelectedIds];

        sessionStorage.setItem('selectedRowKeys', JSON.stringify(this.rowSelection.selectedRowKeys));

        console.log(' this.selectedRowKeys!!!!!!!!!!!!! ', this.selectedRowKeys );
        console.log(' this.rowSelection.selectedRowKeys!!!!!!!!!!!!! ', this.rowSelection.selectedRowKeys );
      } catch (error) {
        console.log(error);
      }
    },

    async delAction(record) {
      try {
        // 传过来的id直接请求删除api
        await ristDelAction({ Id: record.Id })
        this.$message.success(
          this.$t('user.verification-code.required111566110577133')
        )
        // 重新初始化列表刷新数据
        this.actions()
      } catch (error) {
        this.$message.error(error)
      } finally {
      }
    },
    async setActionToRisk() {
      const selectedRowKeysCopy = sessionStorage.getItem('selectedRowKeys');
      // 创建RISk
      this.$refs.createRisk.open(selectedRowKeysCopy,this.actionIdGroups, this.actionDataGroups)
    },
    onChange(value, dateString) {
      console.log('Selected Time: ', value)
      console.log('Formatted Selected Time: ', dateString)
    },
    async onOk(value) {
      const Time = moment(value).format('YYYY-MM-DD HH:mm:ss')
      const { data } = await createSettime({ DpiaNextTime: Time, Id: this.id })
    },
    /*
     * 完成评估
     * @param state
     * @returns {Promise<void>}
     */
    async savePush(state) {

      // 修改状态
      if (state != 'see') {
        await dpiaChangeState({
          Id: this.id,
          DpiaStatus: 4,
        })
        this.$message.success(
          this.$t('user.verification-code.required111566110577308')
        )
        await this.$router.push({ path: '/dpia/service' })
      }

      if (state === 'see') this.exportLoading = true
      else this.buttonLoading = true

      try {
        // 交换意见已达成

        const { data: chinaReport } = await DpiaUpload({ Id: this.id, lang: 1 })
        const { data: englishReport } = await DpiaUpload({ Id: this.id, lang: 2 })

        this.reportUrlC = chinaReport.dpiaReport[0].DpiaReportAddress
        this.reportUrlE = englishReport.dpiaReport[0].DpiaReportAddress

        if (this.pia) {

          if (this.lang === 'zh-CN') {
            sessionStorage.setItem('report', this.reportUrlC)
            this.$router.push({
              path: '/dpia/report',
            })
          } else if (this.lang === 'zh-EN') {
            sessionStorage.setItem('report', this.reportUrlE)
            this.$router.push({
              path: '/dpia/report',
            })
          }
        }

        // const { data: chinaReport } = await axios({
        //   // 用axios发送post请求
        //   method: 'post',
        //   url: process.env.VUE_APP_BASE_API + '/v1/dpia/report/upload', // 请求地址
        //   data: qs.stringify({ Id: this.id, lang: 1 }),
        //   responseType: 'blob', // 表明返回服务器返回的数据类型
        //   headers: {
        //     'Content-Type':
        //       'application/x-www-form-urlencoded; application/octet-stream',
        //     token: storage.get(ACCESS_TOKEN),
        //     tokens: storage.get('bmwToken') || '',
        //     env: process.env.NODE_ENV,
        //   },
        // })

        // const { data: englishReport } = await axios({
        //   // 用axios发送post请求
        //   method: 'post',
        //   url: process.env.VUE_APP_BASE_API + '/v1/dpia/report/upload', // 请求地址
        //   data: qs.stringify({ Id: this.id, lang: 2 }),
        //   responseType: 'blob', // 表明返回服务器返回的数据类型
        //   headers: {
        //     'Content-Type':
        //       'application/x-www-form-urlencoded; application/octet-stream',
        //     token: storage.get(ACCESS_TOKEN),
        //     tokens: storage.get('bmwToken') || '',
        //     env: process.env.NODE_ENV,
        //   },
        // })

        // if (this.pia) {
        // 下载中文报告
        // await this.dumpPdf(chinaReport)
        // 下载英文报告
        // await this.dumpPdf(englishReport)
        // } else {
        // }

      } catch (error) {
        this.$message.error(error)
        console.log(error)
      }
      this.buttonLoading = false
      this.exportLoading = false
    },
    async dumpPdf(content) {
      const blob = new Blob([content], {
        // 下载的文件格式自己在这边更改type的值就好了
        type: 'application/pdf',
      })
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a')
        elink.download = moment() + '.pdf'
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      } else {
        navigator.msSaveBlob(blob, filename)
      }
    },
    editActions(id) {
      // 编辑action
      this.$refs.createAction.open(id, 'edit', true)
    },
    createActions() {
      // 创建Action
      this.$refs.createAction.open()
    },
    async dcoBackoffShow() {
      this.dcoBackoffVisible = true
    },
    async dcoBackoff() {
      // DCO退回
      try {
        await dpiaDcoBackoff({ id: this.id })
        this.$router.push({ path: '/dpia/service' })
        this.$message.success(
          this.$t('user.verification-code.required111566110577272')
        )

        this.dcoBackoffVisible = false
      } catch (error) {
        this.$message.error(error)
        console.log(error)
      }
    },
    async changeChapter(items) {
      try {
        for (var i = 0; i < this.chapterLists.length; i++) {
          this.chapterLists[i].check = false
        }
        // 获取DCO评估结论
        const { data: remarkInfo } = await dpiaDcoRemarkInfo({
          DpiaQid: this.id,
          DpiaChapterId: items.id,
        })
        this.dcoRemark = remarkInfo.DpiaChapterDcoRemark
        this.chapterId = items.id

        items.check = true
        // 默认获取第一章节
        const { data: dpiaSimpleAnswerObject } = await dpiaSimpleAnswer({
          id: this.id,
          DpiaChapterId: items.id,
          lang: this.lang === 'zh-CN' ? 0 : 1,
        })
        const { Page, PageSize, Total, Lists } = dpiaSimpleAnswerObject

        this.dpiaSimpleAnswerLists = Lists
        this.dpiaSimpleAnswerPagination = {
          page: Page,
          pageSize: PageSize,
          total: Total,
        }
      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
    async transfer() {
      // DCO转办
      try {
        if (this.dco == undefined) {
          this.$message.error(
            this.$t('user.verification-code.required111566110577268')
          )
          return
        }

        var dcoName = ''
        for (var i = 0; i < this.userList.length; i++) {
          if (this.userList[i].value == this.dco) {
            dcoName = this.userList[i].label
          }
        }
        await dpiaDcoTransfer({
          id: this.id,
          DpiaDco: dcoName,
          DpiaDcoUserId: this.dco,
        })
        this.$message.success(
          this.$t('user.verification-code.required111566110577269')
        )
        this.visible = false
      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
    async transferShow() {
      // 转办的弹窗
      this.visible = true
      // 获取用户列表下拉
      const { data: userList } = await userQuery(1)

      this.userList = userList
    },
    // async onchange(e) {
    //   console.log(e);
    //   const { data: dpiaSimpleActionObject } = await getItemsChapterRemark({
    //     Id: this.id,
    //     e,
    //     pageSize: 5,
    //   });
    //   const { Page, PageSize, Total, Lists } = dpiaSimpleActionObject;
    //   this.dpiaSimpleEstimateLists = Lists;
    // },

    async actions() {
      // 获取关联的Action
      try {
        // if (this.selectedRowKeys.length > 0) {
        //   this.riskButtom = false
        // }

        const { page, pageSize } = this.dpiaSimpleActionPagination
        // 默认获取第一章节
        if (this.$route.query.isLable == 0) {
          const { data: dpiaSimpleActionObject } = await dpiaSimpleAction({
            Id: this.id,
            page,
            pageSize,
          })
          const { Page, PageSize, Total, Lists } = dpiaSimpleActionObject
          this.dpiaSimpleActionLists = Lists
          this.dpiaSimpleActionPagination = {
            page: Page,
            pageSize: PageSize,
            total: Total,
          }
          // this.rowSelection.selectedRowKeys = this.selectedRowKeys = Lists.filter(
          //   (item) => {
          //     return item.RiskId !== 0
          //   }
          // ).map((item) => {
          //   return item.Id
          // })
          // 多选
          const newSelectedKeys = Lists
            .filter(item => item.RiskId !== 0)
            .map(item => item.Id);
          this.rowSelection.selectedRowKeys = Array.from(new Set([...this.rowSelection.selectedRowKeys, ...newSelectedKeys]));
          this.selectedRowKeys = newSelectedKeys

          // console.log('你看看我是多选1:', this.rowSelection.selectedRowKeys);

        } else if (this.$route.query.isLable == 1) {
          const { data: dpiaSimpleActionObject } = await allDpiaSimpleAction({
            Id: this.id,
            page,
            pageSize,
          })
          const { Page, PageSize, Total, Lists } = dpiaSimpleActionObject
          this.dpiaSimpleActionLists = Lists
          this.dpiaSimpleActionPagination = {
            page: Page,
            pageSize: PageSize,
            total: Total,
          }

          const newSelectedKeys = Lists
            .filter(item => item.RiskId !== 0)
            .map(item => item.Id);
          this.rowSelection.selectedRowKeys = Array.from(new Set([...this.rowSelection.selectedRowKeys, ...newSelectedKeys]));
          this.selectedRowKeys = newSelectedKeys
        }
      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
    async estimates() {
      // 获取评估意见列表
      try {
        const { page, pageSize } = this.dpiaSimpleEstimatePagination
        // 默认获取第一章节
        const { data: dpiaSimpleEstimateObject } = await getItemsChapterRemark({
          Id: this.id,
          page,
          pageSize: 100,
        })
        const { Page, PageSize, Total, Lists } = dpiaSimpleEstimateObject
        //获取转办详情
        const { data } = await transferDetails({ Id: this.id })
        this.transferList = data
        this.dpiaSimpleEstimateLists = Lists
        var tempLists = []
        for (var i = 0; i < this.dpiaSimpleEstimateLists.length; i++) {
          if (this.dpiaSimpleEstimateLists[i].DpiaChapterDcoRemark) {
            this.dpiaSimpleEstimateLists[i].DpiaChapterDcoRemark =
              this.dpiaSimpleEstimateLists[i].DpiaChapterDcoRemark.join('<br>')
            tempLists.push(this.dpiaSimpleEstimateLists[i])
          }
        }
        this.dpiaSimpleEstimateLists = tempLists
        // console.log('dpiaSimpleEstimateLists:', this.dpiaSimpleEstimateLists)

        this.dpiaSimpleEstimatePagination = {
          page: Page,
          pageSize: 5,
          total: Total,
        }
      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
    async risks() {
      // 获取关联的RISK
      try {
        this.riskButtom = true
        const { page, pageSize } = this.dpiaSimpleRiskPagination
        // 默认获取第一章节
        if (this.$route.query.isLable == 0) {
          const { data: dpiaSimpleRiskObject } = await dpiaRiskLists({
            Id: this.id,
            page,
            pageSize,
          })
          console.log(dpiaSimpleRiskObject)
          const { Page, PageSize, Total, Lists } = dpiaSimpleRiskObject
          this.dpiaSimpleRiskLists = Lists
          this.dpiaSimpleRiskPagination = {
            page: Page,
            pageSize: PageSize,
            total: Total,
          }
          this.getAllSelectedData();
        } else if (this.$route.query.isLable == 1) {
          const { data: dpiaSimpleRiskObject } = await allDpiaRiskLists({
            Id: this.id,
            page,
            pageSize,
          })
          console.log(dpiaSimpleRiskObject)
          const { Page, PageSize, Total, Lists } = dpiaSimpleRiskObject
          this.dpiaSimpleRiskLists = Lists
          this.dpiaSimpleRiskPagination = {
            page: Page,
            pageSize: PageSize,
            total: Total,
          }
        }
        this.getAllSelectedData();
      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
    async init() {
      try {
        // 初始化题库
        this.id = this.$route.query.id
        var id = this.$route.query.id
        //初始化页面状态
        const state = this.$route.query.state
        //区分是整体评估还是查看
        this.state = state

        // 获取初步评估Action
        await this.actions()

        // 获取RISK
        await this.risks()

        // 获取评估的意见
        await this.estimates()

        // 基础信息查询
        const { data: questionnaireInfo } = await dpiaQuestionInfo({
          id: this.id,
        })
        const { data: rpaDetails } = await quesionFindRpaId({ Id: id })
        // 获取RPA详情
        const { data: rpaDetailInfo } = await rpaDetail({
          Id: rpaDetails.DpiaRpaId,
        })
        this.RpaPIALinkUrl = rpaDetailInfo.RpaPIALinkUrl
        this.RpaIfCompletedPIA = rpaDetailInfo.RpaIfCompletedPIA
        if (
          rpaDetailInfo.RpaIfCompletedPIA == 1 ||
          rpaDetailInfo.RpaNoPIOrImportantInvolved == 1
        ) {
          this.pia = false
        } else {
          this.pia = true
        }
        this.questionnaireInfo = questionnaireInfo

        //获取下次评估时间
        const { data: DpiaNextTime } = await getNextTime({ Id: this.id })
        this.DpiaNextTime = DpiaNextTime.DpiaNextTime
          ? DpiaNextTime.DpiaNextTime
          : null
      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
    async pageInit(obj) {
      this.dpiaQuestionUserAnswer = obj
      try {
        // 获取答案
        if (this.dpiaQuestionUserAnswer != {}) {
          // 把答题的结果拿到
          await dpiaQuestionAnswerCreate({
            DpiaChapterId: this.dpiaQuestionUserAnswer.chapter,
            DpiaQid: this.id,
            DpiaChapterTopicId: this.dpiaQuestionUserAnswer.topic,
            DpiaChapterTopicAnswer: encodeURIComponent(vthis.dpiaQuestionUserAnswer.answer),
            DpiaChapterTopicType: this.dpiaQuestionTopicAnswer.topic.type,
          })

          // 清空答案
          this.dpiaQuestionUserAnswer = {}
        }
      } catch (error) {
        console.log('error:', error)
        this.$message.error(error)
      }
    },
    async showModal() {
      this.visible = true
      // 获取用户列表下拉
      const { data: userList } = await userQuery(1)

      this.userList = userList
    },
    async handleOk(e) {
      // 交卷
      if (this.dco == undefined) {
        this.$message.error(
          this.$t('user.verification-code.required111566110577268')
        )
        return
      }
      try {
        await dpiaQuestionChangeStatus({
          Id: this.id,
          DpiaStatus: 2,
          DpiaDcoUserId: this.dco,
        })
        this.$message.success(
          this.$t('user.verification-code.required111566110577270')
        )
      } catch (error) {
        this.$message.error(error)
      }

      this.topicShow()
      this.visible = false
      // 开启那个结果页
      this.finishStatus = 1
    },
    rollback() {
      this.$router.push('/dpia/service')
    },
    returnChapter() {
      let _this = this
      this.$confirm({
        title: this.$t('user.verification-code.returnchapterconform'),
        okText: this.$t('user.email.required1111'),
        cancelText: this.$t('user.email.required11'),
        async onOk() {
          let res = await dpiaChangeState({
            Id: _this.id,
            DpiaStatus: 2,
          })
          if (res.code === 1) {
            let record = _this.$route.query
            const res = await isWithdraw({ Id: record.Id })
            if (res.data == 0) {
              _this.$message.error('不可评估')
              return
            }
            // DCO评估
            _this.$router.push({
              path: '/dpia/onequestion/estimate',
              query: {
                ..._this.$route.query,
                id: record.Id,
                DpiaCreateUserId: record.DpiaCreateUserId,
                DpiaChangeDcoId: record.DpiaChangeDcoId || '',
                DpiaId: record.DpiaId,
                ChangeCommit: record.Role ? record.Role.CHANGE : record.CHANGE,
                ifDco: record.Role ? record.Role.DCO : record.ifDco,
              },
            })
            localStorage.setItem('ifchaning', true)
          }
        },
      })
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-card-body {
  // display: flex;

  .buttomm {
    width: 100%;
  }

  .card-box {
    font-size: 15.5px;
    display: flex;
  }

  .card-left {
    /*rectangle copy 4备份 87*/
    margin: 20px 30px 20px 20px;
    color: #444e84;
    left: 339px;
    top: 287px;
    width: 388px;
    height: 428px;
    opacity: 0.67;
    border-radius: 2px;
    background: #f7faff;

    ul {
      margin-top: 10px;
    }

    ul li {
      padding: 3px;
    }
  }

  .left-title {
    color: #050c34;
    width: 100%;
    line-height: 40px;
    padding: 0 10px;
    padding-left: 20px;
    background: #e7f0ff;
    border-bottom: 1px solid #ddd;
  }

  .card-right {
    margin: 20px 20px 20px 20px;
  }

  p {
    color: #000;
  }
}

.tags {
  left: 298px;
  top: 288px;
  width: 6px;
  height: 14px;
  opacity: 1;
  border-radius: 2px;
  background: rgba(0, 80, 247, 1);
}

.ant-card {
  overflow: auto;
  height: auto;
}

.card-right {
  margin: 30px 30px 30px 60px;
}

</style>